#数据打勾标签图

import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.cbook as cbook

# 设置日期定位器和格式化器
years = mdates.YearLocator()   # 每年一个刻度
months = mdates.MonthLocator()  # 每月一个刻度
yearsFmt = mdates.DateFormatter('%Y')

# 从mpl-data/example目录加载包含日期、开盘价、收盘价、交易量和调整收盘价的npz文件
fname = cbook.get_sample_data('goog.npz', asfileobj=False)
with np.load(fname) as datafile:
    r = datafile['price_data'].view(np.recarray)

# 创建图形和坐标轴对象
fig, ax = plt.subplots()

# 绘制调整收盘价数据
ax.plot(r.date, r.adj_close)

# 格式化刻度
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)

# 设置x轴的范围
datemin = np.datetime64(r.date[0], 'Y')
datemax = np.datetime64(r.date[-1], 'Y') + np.timedelta64(1, 'Y')
ax.set_xlim(datemin, datemax)

# 格式化数据坐标框
def price(x):
    return '$%1.2f' % x

ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
ax.format_ydata = price
ax.grid(True)

# 自动旋转和对齐x轴标签
fig.autofmt_xdate()

# 显示图形
plt.show()